// pages/agent/index.js
const app = getApp()
const {
  messageset,
  messagetop,
  pay,
  messagerecruit,
  messagefabu,
  messageedit,
  editrecruit
} = require('../../utils/api')
const {
  fetch,
  newFetch,
  filteremoji,
  hasSensitiveWords,
  replaceAll
} = require('../../utils/fetch')
const {
  BASEURL
} = require('../../utils/baseurl')
import {
  Base
} from '../../utils/base.js';
var base = new Base();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    type: '',
    type_id: 0,
    sub_type_id: 0,
    sub_type_info: [],

    title: '',
    details: '', //描述
    address: '',

    pushName: '',
    pushPhone: '',

    region: ['请选择地区', '', ''],
    postcode: 102300,
    provincity: ["110000", "110100", "110101"],

    checked1: true,

    formId: '',
    specificarea: null,
    systemInfo: '',
    isApply: true,
    pubdisabled:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if (wx.getStorageSync('specificarea')) {
      this.setData({
        specificarea: wx.getStorageSync('specificarea')
      })
    }

    if (wx.getStorageSync('userInfo')) {
      let userInfo = wx.getStorageSync('userInfo');
      this.setData({
        pushPhone: userInfo.mobile,
        pushName: userInfo.nickname
      })
    }
    if (wx.getStorageSync('currentAddress')) {
      let addressval = wx.getStorageSync('currentAddress').address_component;
      let rgaddress = [addressval.city, addressval.province, addressval.district]
      this.setData({
        region: rgaddress
      })
    }

    wx.getSystemInfo({
      success: function (res) {
        if (res.system.indexOf('iOS') == 0) {
          that.setData({
            systemInfo: 'iOS'
          })
        } else {
          that.setData({
            systemInfo: 'Android'
          })
        }
      }
    })
    this.initapply(app.globalData.currentAddress.ad_info.adcode) //判断区域是否申请
  },

  initapply(applyarea) {
    var that = this;
    newFetch(`wx/member/${this.data.specificarea}/validArea`, 'get', {
      county: applyarea
    }).then(res => {
      if (res.code == 200) {
        that.setData({
          isApply: false
        })
      }
      if (res.code == 400) {
        that.setData({
          isApply: true
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  onChange1(event) {
    this.setData({
      checked1: event.detail
    })
  },
  onChange(event) {},
  jumpToAgreement() {
    wx.navigateTo({
      url: '/pages/login/agreement'
    })
  },
  // 输入框的联系人值
  goinputpushName: function (e) {
    this.setData({
      pushName: e.detail.value
    })
  },
  // 输入框的电话值
  goinputpushPhone: function (e) {
    this.setData({
      pushPhone: e.detail.value
    })
  },
  // 地址选择
  bindRegionChange: function (e) {
    var val_arr = e.detail.value;
    var that = this;
    if (val_arr[0] == '全部' && val_arr[1] == '全部' && val_arr[2] == '全部') {
      this.setData({
        region: ['请选择地区']
      })
      return;
    }
    this.initapply(e.detail.code[2])
    this.setData({
      region: e.detail.value,
      // postcode: e.detail.postcode,
      provincity: e.detail.code,
      pubdisabled:false
    })
  },
  // 申请
  publishFN: function (e) {
    var that = this;
    if (!this.data.checked1) {
      wx.showToast({
        title: '请先同意代理商协议',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    this.setData({
      formId: e.detail.formId
    })
    if (this.data.region.indexOf('请选择地区') == 0) {
      this.showToast('请选择地区');
      return;
    }
    wx.showLoading({
      title: '申请中',
    })
   this.setData({
    pubdisabled:true
   })

    let userInfo = wx.getStorageSync('userInfo');
    var re_param = {
      memberId: userInfo["id"],
      county: this.data.provincity[2],
      city: this.data.region,
    };

    fetch(`wx/member/${this.data.specificarea}/apply`, 'POST', re_param).then(res => {
      if (res) {
        if (that.data.systemInfo == 'iOS') {
          wx.showToast({
            title: 'iOS不支持虚拟支付',
            icon: 'none',
            duration: 1500
          })
          return;
        }
        fetch(`wx/member/${this.data.specificarea}/getSysSet`, 'POST').then(resset => {
          if (resset) {
            wx.hideLoading()
            that.pay(res.id, res.orderId, resset.value);
          }
        })
      }
    })
  },
  pay: function (typeId, orderId, money) {
    var that = this;
    let userInfo = wx.getStorageSync('userInfo');
    let obg = {
      // area: this.data.specificarea,
      county: this.data.provincity[2],
      openId: userInfo['openid'],
      memberId: userInfo['id'],
      // money: '0.01',
      money: money,
      orderdesc: '小微服务',
      orderId: orderId,
      type: 5,
      typeId: typeId,
      formId: that.data.formId
    }
    fetch(`wx/pay/${this.data.specificarea}/pay`, 'POST', obg).then(info => {
      wx.requestPayment({
        timeStamp: info.timeStamp,
        nonceStr: info.nonceStr,
        package: `prepay_id=${info.prepayId}`,
        signType: 'MD5',
        paySign: info.paySign,
        success: function (res) {
          wx.showToast({
            title: '付款成功',
            icon: 'success',
            duration: 2000
          })
          that.endjump();
        },
        fail: function (res) {
          that.setData({
            pubdisabled:false
          })
          wx.showToast({
            title: '取消付款成功',
            icon: 'success',
            duration: 2000
          })
        }
      })
    })
  },

  endjump: function () {
    setTimeout(() => {
      wx.redirectTo({
        url: '/pages/showmsg/index?id=' + 'agent',
      })
    }, 3000)
  },
})